package org.yesin.auth.web;

import com.yesin.geteway.utils.CookieUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.yesin.auth.config.JwtProperties;
import org.yesin.auth.entity.UserInfo;
import org.yesin.auth.service.AuthService;
import org.yesin.auth.utils.JwtUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@RestController
@EnableConfigurationProperties(JwtProperties.class)
public class AuthController {

    @Autowired
    private AuthService authService;

    @Autowired
    private JwtProperties pro;

    @PostMapping("accredit")
    public ResponseEntity<Void> accredit(
            @RequestParam("username")String username,
            @RequestParam("password")String password,
            HttpServletRequest request,
            HttpServletResponse response){
        String token = this.authService.accredit(username, password);
        if (StringUtils.isBlank(token)){
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
        }
        CookieUtils.setCookie(request, response, pro.getCookieName(), token, pro.getExpire() * 60);
        return ResponseEntity.ok().build();
    }

    @GetMapping("verify")
    public ResponseEntity<UserInfo> verify(
            @CookieValue("YS_TOKEN") String token,
            HttpServletRequest request,
            HttpServletResponse response){

        try {
            // 通过Jwt工具类来解析token
            UserInfo user = JwtUtils.getInfoFromToken(token, pro.getPublicKey());
            if (user == null){
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            // 刷新jwt有效时间
            token = JwtUtils.generateToken(user, pro.getPrivateKey(), pro.getExpire());
            // 刷新cookie有效时间
            CookieUtils.setCookie(request, response, pro.getCookieName(),token, pro.getExpire() * 60);
            return ResponseEntity.ok(user);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
    }
}
